from rest_framework.views import APIView
from utils.cloud_aliyun import AliCloud
from rest_framework.response import Response
from rest_framework import status
from rest_framework.exceptions import ValidationError
from asset.models import *
import os, json, time
from django.db.models import Q

from utils.custom_log   import log_start
logger = log_start('aliyun')

class AliyunCloudRegionView(APIView):
    """
    阿里云获取云主机信息
    """
    # 获取地区(region)
    def post(self, request):
        print("AliyunCloudView")
        print(request.query_params)
        secret_id = request.data.get('secret_id')
        secret_key = request.data.get('secret_key')
        cloud = AliCloud(secret_id, secret_key)
        result = cloud.region_list()
    
        if result['code'] == 200:
            data = []
            for r in result['data']['Regions']['Region']:
                rg = {'region_id': r['RegionId'], 'region_name': r['LocalName']}
                ## 统计区域ECS数量
                region = rg['region_id']
                logger.info(f"区域: {region}")
                data.append(rg)
            
            if len(data) >1:
                data = {'detail': '获取区域列表', 'results': data}
                return Response(data=data)
            else:
                return Response(data={'detail': '获取区域列表失败!'}, status=status.HTTP_400_BAD_REQUEST)  
        else:
            return Response(data={'detail': '读取失败,请检查AK是否有效!'}, status=status.HTTP_400_BAD_REQUEST)  
            

        



class AliyunCloudUpdateView(APIView):

    ## 导入云主机信息到数据库
    def post(self, request):
        print(request.data)
        secret_id = request.data.get('secret_id')
        secret_key = request.data.get('secret_key')
        server_group_ids = request.data.get('server_group')
        region_id = request.data.get('region')  # 区域用于机房里的城市
        connect_type = request.data.get('connect_type')  # 用户选择使用内网（private）还是公网（public），下面判断对应录入
        ssh_id = request.data.get('ssh_id')

        cloud = AliCloud(secret_id, secret_key)
        result = cloud.instance_list(region_id)
        logger.error(result)

        if result['code']  == 200:
            instance_list = result['data']
            # instance_list = result['data']['Instances']['Instance']
            if len(instance_list) == 0:
                res = {'code': 500, 'msg': '该区域未发现云主机，请重新选择！'}
                return Response(res)
        else:
            res = {'code': 500, 'msg': '%s' %result['msg']}
            return Response(res)

        # 根据地区获取可用区
        zone_result = cloud.zone_list(region_id)
        zone_dict = {}  # {'cn-beijing-k': '华北 2 可用区 K'}
        for z in zone_result['data']['Zones']['Zone']:
            zone_dict[z['ZoneId']] = z['LocalName']

        # 根据云主机里zoneid获取对应的zone中文名
        zone_set = set()  # ('华北 2 可用区 K','华北 2 可用区 H')
        for host in instance_list:
            zone = host['ZoneId']
            zone_set.add(zone_dict[zone])


        ssh_instance = SSH_account.objects.get(id=ssh_id)

        platform = Platform.objects.filter(name='阿里云')
        if not platform:
            Platform.objects.create(
                    name="阿里云"
                )
        platform_instance = Platform.objects.get(name='阿里云')

        # 根据可用区
        for zone in zone_set:
            # 如果机房不存在则创建
            region = Region.objects.filter(region=zone)
            if not region:
                # 获取region的中文名
                region_list = cloud.region_list()['data']['Regions']['Region']
                for r in region_list:
                    if r['RegionId'] == region_id:
                        city = r['LocalName']
                Region.objects.create(
                    region=zone,
                    city=city,
                )

        for host in instance_list:
            instance_name = host['InstanceName'] # 机器名称
            hostname = host['HostName'] # 主机名
            instance_id = host['InstanceId']
            os_version = host['OSName']
       

            private_ip_list = host['NetworkInterfaces']['NetworkInterface'][0]['PrivateIpSets']['PrivateIpSet']
            private_ip = []
            for ip in private_ip_list:
                private_ip.append(ip['PrivateIpAddress'])

            public_ip = host['PublicIpAddress']['IpAddress']
            floatingip = public_ip[0] if public_ip else ""
            
            cpu = "%s核" %host['Cpu']
            memory = "%sG" %(int(host['Memory']) / 1024)

            ## 硬盘信息需要单独获取
            disk = []
            disk_list = cloud.instance_disk(instance_id)['data']['Disks']['Disk']
            for d in disk_list:
                disk.append({'device': d['Device'], 'size': '%sG' % d['Size'], 'type': None})
            print(disk,type(disk))
            logger.error(f'{disk}')

            create_date = time.strftime("%Y-%m-%d", time.strptime(host['CreationTime'], "%Y-%m-%dT%H:%MZ"))
            # 2022-01-30T04:51Z 需要转换才能存储
            expired_time = time.strftime("%Y-%m-%d %H:%M:%S", time.strptime(host['ExpiredTime'], "%Y-%m-%dT%H:%MZ"))
           
    
            ## 根据实例id判断是否重复
            # newServer = Host.objects.filter(instance_id = instance_id )
            newServer = Host.objects.filter(Q(instance_id = instance_id) | Q(hostname=instance_name))
            if not newServer:
                zone = host['ZoneId']
                region_name = zone_dict[zone]
                region_instance = Region.objects.get(region=region_name)
                

               
                newServer = Host.objects.create(
                   
                    hostname=instance_name,
                    instance_id= instance_id,
                    region_id=region_instance,
                    platform_id = platform_instance,
                    ssh_id = ssh_instance,
                    asset_type ='cloud_aliyun_host',
                    os_version=os_version,
                    floatingip=floatingip,
                    ip=private_ip[0],
                    cpu=cpu,
                    memory=memory,
                    disk=disk,
                    connect_type=connect_type,
                    gmt_create=create_date,
                    expire_time=expired_time,

                )
                # 添加多对多字段
                for group_id in server_group_ids:
                    group = Group.objects.get(id=group_id)  # 获取分组
                    newServer.group_id.add(group)  # 将服务器添加到分组
            else:
                logger.error(f"[ {hostname} ] 已存在！")

        data = { 'code': 20000,'detail':  '导入云主机成功'}
        return Response(data=data)